package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {


    @Autowired
    private DeptService deptService;


    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));

        // 构建一个Wrapper对象，用来封装查询条件
//        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(param.getName()!= null && !param.getName().isEmpty(),Emp::getName, param.getName())
//                .eq(param.getGender() != null, Emp::getGender,param.getGender())
//                .between(param.getBegin() != null && param.getEnd() !=null,Emp::getEntryDate,param.getBegin(), param.getEnd());
//
//
//        //调用Service层查询分页数据
//        page = page(page,queryWrapper);

        // 借助于 lambdaQuery()方法，构建查询条件， 同时获取分页结果
        page = lambdaQuery().like(param.getName()!= null && !param.getName().isEmpty(),Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender,param.getGender())
                .between(param.getBegin() != null && param.getEnd() !=null,Emp::getEntryDate,param.getBegin(), param.getEnd())
                .page(page);


        List<Emp> emps = page.getRecords();


        // 遍历emps结果，添加部门名称
        emps.forEach(e -> {
            Dept dept = deptService.getById(e.getDeptId());
            if (dept != null && !dept.getName().isEmpty()) {
                e.setDeptName(dept.getName());
            }
        });

        return new PageResult<>(page.getTotal(), emps);
    }
}